package com.ruoyi.comment.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.comment.service.ISysCommentService;
import com.ruoyi.comment.domain.SysComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comment")
public class SysCommentController {

    @Autowired
    private ISysCommentService commentService;

    /**
     * 提交评论
     */
    @PostMapping("/submit")
    public AjaxResult submitComment(@RequestBody SysComment comment) {
        // 获取用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser(); // 确保用户已登录
        SysUser user = loginUser.getUser();

        if (user == null) {
            return AjaxResult.error("用户未登录");
        }

        // 校验必要字段
        if (comment.getOrderId() == null || comment.getContent() == null || comment.getContent().trim().isEmpty()) {
            return AjaxResult.error("订单ID和评论内容不能为空");
        }

        // 设置评论用户信息
        comment.setUserId(user.getUserId());
        comment.setUsername(user.getUserName());

        // 保存评论
        commentService.saveComment(comment);
        return AjaxResult.success("评论提交成功");
    }


    /**
     * 获取订单下的所有评论
     */
    @GetMapping("/list")
    public AjaxResult getCommentsByOrderId(Long orderId) {
        List<SysComment> comments = commentService.getCommentsByOrderId(orderId);
        return AjaxResult.success("comments", comments);
    }

    /**
     * 删除指定ID的评论
     */
    @DeleteMapping("/delete")
    public AjaxResult deleteComment(Long commentId) {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        SysComment comment = commentService.getCommentById(commentId);

        if (comment == null) {
            return AjaxResult.error("评论不存在");
        }

        // 判断当前用户是否有权限删除（自己评论 or 管理员）
        if (!comment.getUserId().equals(currentUser.getUserId())
                && !currentUser.isAdmin()) {
            return AjaxResult.error("无权限删除");
        }

        commentService.deleteCommentById(commentId);
        return AjaxResult.success("评论删除成功");
    }
}
